package com.bmob.lover.ui.fragment.user

import android.os.Bundle
import android.view.Gravity
import android.view.View
import androidx.fragment.app.viewModels
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction
import com.theone.common.callback.OnKeyBackClickListener
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.getValueNonNull
import com.theone.common.ext.isPhoneNumber
import com.theone.common.ext.trimAll
import com.bmob.lover.R
import com.bmob.lover.data.model.enums.TYPE_FORGET_PASSWORD
import com.bmob.lover.data.model.enums.TYPE_MODIFY_PASSWORD
import com.bmob.lover.data.model.enums.TYPE_REGISTER
import com.bmob.lover.databinding.FragmentSendVerifyCodeBinding
import com.bmob.lover.viewmodel.SendVerifyCodeViewModel
import com.bmob.lover.viewmodel.request.UserListRequestViewModel
import com.theone.mvvm.core.base.fragment.BaseCoreFragment
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.ext.qmui.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-04-19 13:58
 * @describe 发送验证码
 * @email 625805189@qq.com
 * @remark
 */
class SendVerifyCodeFragment private constructor() :
    BaseCoreFragment<SendVerifyCodeViewModel, FragmentSendVerifyCodeBinding>() {

    companion object {
        fun newInstance(type: Int, phoneNumber: String? = ""): SendVerifyCodeFragment {
            return SendVerifyCodeFragment().apply {
                arguments = Bundle().apply {
                    putInt(BundleConstant.TYPE, type)
                    putString(BundleConstant.DATA, phoneNumber)
                }
            }
        }
    }

    private val mUserRequestVm: UserListRequestViewModel by viewModels()
    private val mType: Int by getValueNonNull(BundleConstant.TYPE)
    private val mPhoneNum: String by getValueNonNull(BundleConstant.DATA)

    override fun getLayoutId(): Int = R.layout.fragment_send_verify_code

    override fun initView(root: View) {
        getTopBar()?.run {
            setTitleWithBackBtn(
                if (mType == TYPE_REGISTER) R.string.register_string else R.string.forget_password,
                this@SendVerifyCodeFragment
            )
            setTitleGravity(Gravity.START)
            updateBottomDivider(0, 0, 0, 0)
        }
        getViewModel().phone.set(mPhoneNum)
    }

    override fun createObserver() {
        addFailTipsObserve(getViewModel(), mUserRequestVm)
        getViewModel().run {
            getResponseLiveData().observe(this@SendVerifyCodeFragment) {
                hideLoadingDialog()
                context?.showSuccessTipsDialog("发送成功") {
                    startFragmentAndDestroyCurrent(
                        if (mType == TYPE_FORGET_PASSWORD) {
                            ResetPasswordFragment.newInstance(phoneNumber, mType)
                        } else {
                            RegisterFragment.newInstance(phoneNumber)
                        }
                    )
                }
            }
        }
        mUserRequestVm.getResponseLiveData().observe(this) {
            // 为空说明该手机号码没有注册过
            if (it.isNullOrEmpty()) {
                // 没有注册，忘记密码功能不能使用
                if (mType == TYPE_FORGET_PASSWORD) {
                    showFailTips("该手机号码未注册,请使用注册功能", TYPE_REGISTER)
                    return@observe
                }
                if (mType == TYPE_MODIFY_PASSWORD) {
                    showFailTips("该手机号码未注册", TYPE_MODIFY_PASSWORD)
                    return@observe
                }
            } else {
                // 已经注册了，那么注册的功能不能使用
                if (mType == TYPE_REGISTER) {
                    showFailTips("该手机号码已注册,请使用找回密码", TYPE_FORGET_PASSWORD)
                    return@observe
                }
            }
            // 发送短信请求
            getViewModel().requestServer()
        }
    }

    private fun showFailTips(msg: String, type: Int) {
        hideLoadingDialog()
        val isModify = type == TYPE_MODIFY_PASSWORD
        context?.showMsgDialog(
            "提示",
            msg,
            leftAction = if (isModify) null else "关闭",
            listener = QMUIDialogAction.ActionListener { dialog, index ->
                dialog?.dismiss()
                if (!isModify && index > 0) {
                    startFragmentAndDestroyCurrent(
                        newInstance(
                            type, getViewModel().phoneNumber
                        )
                    )
                }
            })?.apply {
            setCanceledOnTouchOutside(false)
            setOnKeyListener(OnKeyBackClickListener())
        }
    }

    override fun getBindingClick() = ProxyClick()

    inner class ProxyClick {

        fun sendVerifyCode() {

            with(getViewModel()) {
                phoneNumber = phone.get().trimAll()
                if (phoneNumber.isPhoneNumber()) {
                    // 发送短信前检查下发送短信的手机号码是否已注册
                    showLoadingDialog("发送中")
                    mUserRequestVm.phoneNumber = phoneNumber
                    mUserRequestVm.requestServer()
                } else {
                    showFailTipsDialog("手机号码不符合规范")
                }
            }

        }

        fun clear() {
            getViewModel().phone.set("")
        }

    }

}